using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using HslCommunicationEx;

namespace AcqEncoder.TcpIp
{
	public abstract class RemoteTcpClient
	{
		public int ReadInterval = 50;

		private bool _readFlag = true;

		public Task _readTask;

		public Action<string, int> ReadOutHandler;

		public TcpClient Client { get; }

		public string UserName { get; set; } = "";


		public string UserIp { get; set; }

		public int UserPort { get; set; }

		public byte[] RcvByteBuf { get; set; }

		public int TimeReadOut { get; set; }

		protected int SumTime { get; set; }

		public Thread TdRead { get; set; }

		public bool IsReadMutiThread { get; set; }

		public Task TaskReadTask => this._readTask;

		public bool IsReadTaskCompleted => this._readTask?.IsCompleted ?? false;

		protected RemoteTcpClient(TcpClient client)
		{
			if (client == null)
			{
				throw new ArgumentNullException("client");
			}
			EndPoint? remoteEndPoint = client.Client.RemoteEndPoint;
			this.UserIp = ((remoteEndPoint != null) ? remoteEndPoint!.ToString()!.Split(':')[0] : null);
			if (client.Client.RemoteEndPoint != null)
			{
				this.UserPort = int.Parse(client.Client.RemoteEndPoint!.ToString()!.Split(':')[1]);
			}
			this.Client = client;
		}

		public virtual OperateRet StartReadTask()
		{
			OperateRet operateRet = new OperateRet();
			if (this._readTask?.IsCompleted ?? false)
			{
				operateRet.Message = "当前任务尚未结束!";
				return operateRet;
			}
			this._readTask = Task.Factory.StartNew(new Action(RcvData), TaskCreationOptions.LongRunning);
			operateRet.Success = true;
			return operateRet;
		}

		public virtual void Dispose()
		{
			this.Client.Close();
		}

		public virtual void RcvData()
		{
		}

		public bool? SendData(string msg)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(msg);
			return this.SendData(bytes);
		}

		public virtual bool? SendData(byte[] sendBuf)
		{
			TcpClient client = this.Client;
			return client != null && client.Client.Send(sendBuf) > 0;
		}
	}
}
